package com.bjgzy.rating.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.format.Formatter;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bjgzy.rating.R;
import com.bjgzy.rating.R2;
import com.bjgzy.rating.di.component.DaggerSignUp3Component;
import com.bjgzy.rating.di.module.SignUp3Module;
import com.bjgzy.rating.mvp.contract.SignUp3Contract;
import com.bjgzy.rating.mvp.model.entity.SignUp3Data;
import com.bjgzy.rating.mvp.model.entity.SignUp3Json;
import com.bjgzy.rating.mvp.presenter.SignUp3Presenter;
import com.bjgzy.rating.mvp.ui.adapter.UploadAdapter;
import com.blankj.utilcode.util.ObjectUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.RatingHomeData;
import com.eduhzy.ttw.commonsdk.entity.SignUp2Data;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.google.gson.Gson;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author xubo
 * @date 2018-8-26 17:08:16
 */
@Route(path = RouterHub.RATING_SIGNUP3ACTIVITY)
public class SignUp3Activity extends BaseActivity<SignUp3Presenter> implements SignUp3Contract.View {
    private int themeId = R.style.public_picture_white_style;
    @Autowired(name = Constants.ROUTER_DATA)
    SignUp2Data mData;
    @Autowired(name = Constants.PARCELABLE_DATA)
    RatingHomeData mHomeData;

    @BindView(R2.id.btn_submit)
    QMUIRoundButton mBtnSubmit;
    @BindView(R2.id.tv_type_label)
    TextView mTvTypeLabel;
    @BindView(R2.id.tv_no_upload)
    TextView mTvNoUpload;
    @BindView(R2.id.tv_tip_label)
    TextView mTvTipLabel;
    @BindView(R2.id.rv_list)
    RecyclerView mRvList;
    @Inject
    UploadAdapter mAdapter;
    @Inject
    List<SignUp3Data> lists;
    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    Gson mGson;
    private List<LocalMedia> selectList = new ArrayList<>();

    int[] imgIds = {R.drawable.img_shipin, R.drawable.img_shipin, 0, R.drawable.img_zhaopian, R.drawable.img_luyin};
    int[] strTypeIds = {R.string.rating_type_common, R.string.rating_type_video, R.string.rating_type_doc, R.string.rating_type_pic, R.string.rating_type_audio};
    int[] strTipeIds = {R.string.rating_upload_common, R.string.rating_upload_video, R.string.rating_upload_doc, R.string.rating_upload_pic, R.string.rating_upload_audio};
    private int mMaxSelectNum;
    private int mSelectionMode;
    private int mMimeType;
    private QMUITipDialog mDialog;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        //如找不到该类,请编译一下项目
        DaggerSignUp3Component
                .builder()
                .appComponent(appComponent)
                .signUp3Module(new SignUp3Module(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        return R.layout.rating_activity_sign_up3;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mBtnSubmit.setChangeAlphaWhenPress(true);
//        mAdapter.addFooterView()
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(mLayoutManager);
        initListener();
    }

    private void initListener() {
        View footer = View.inflate(getActivity(), R.layout.rating_rv_item_upload_add, null);
        QMUIAlphaButton iv = footer.findViewById(R.id.iv_icon);
        iv.setBackgroundResource(imgIds[mData.getFileType()]);
        String fileSize = Formatter.formatFileSize(this, Long.valueOf(mData.getMaxSize()));
        mTvTypeLabel.setText(getString(strTypeIds[mData.getFileType()]));
        mTvTipLabel.setText(String.format(getString(strTipeIds[mData.getFileType()], mData.getMaxNum(), fileSize)));
        iv.setOnClickListener(v -> {
            if (lists.size() == mData.getMaxNum()) {
                showMessage("最多添" + mData.getMaxNum() + "个文件");
                return;
            }
            mMaxSelectNum = mData.getMaxNum();
            mSelectionMode = mMaxSelectNum > 1 ? PictureConfig.MULTIPLE : PictureConfig.SINGLE;
            switch (mData.getFileType()) {
                case Constants.FILETYPE.COMMON:
                    mMimeType = PictureMimeType.ofAll();
                    break;
                case Constants.FILETYPE.VIDEO:
                    mMimeType = PictureMimeType.ofVideo();
                    break;
                case Constants.FILETYPE.PICTURE:
                    mMimeType = PictureMimeType.ofImage();
                    break;
                case Constants.FILETYPE.AUDIO:
                    mMimeType = PictureMimeType.ofAudio();
                    break;
                default:
            }
            PictureSelector.create(getActivity())
                    .openGallery(mMimeType)
                    .theme(themeId)
                    .maxSelectNum(mMaxSelectNum)
                    .minSelectNum(1)
                    .selectionMode(mSelectionMode)
                    .previewVideo(true)
                    .previewImage(true)
                    .enablePreviewAudio(true)
                    .isCamera(true)
//                        .enableCrop(cb_crop.isChecked())
//                        .compress(cb_compress.isChecked())
//                        .rotateEnabled(false) // 裁剪是否可旋转图片
                    .glideOverride(160, 160)
                    .previewEggs(true)
                    .selectionMedia(selectList)
                    .forResult(PictureConfig.CHOOSE_REQUEST);

        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            SignUp3Data data = lists.get(position);
            if (data.isUploading()) {
                showMessage("上传完成后才可操作");
                return;
            }

            int mimeType = data.getLocalMedia().getMimeType();
            if (mimeType == PictureMimeType.ofVideo()) {
                // 预览视频
                if (ObjectUtils.isEmpty(data.getUrl())) {
                    showMessage("视频转换中，请稍后");
                    return;
                }
                PictureSelector.create(getActivity()).externalPictureVideo(data.getLocalMedia().getPath());
            } else if (mimeType == PictureMimeType.ofImage()) {
                PictureSelector.create(getActivity()).themeStyle(themeId).openExternalPreview(position, selectList);
            } else if (mimeType == PictureMimeType.ofAudio()) {
                if (ObjectUtils.isEmpty(data.getUrl())) {
                    showMessage("音频转换中，请稍后");
                    return;
                }
                PictureSelector.create(getActivity()).externalPictureAudio(data.getLocalMedia().getPath());
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (lists.get(position).isUploading()) {
                showMessage("上传完成后才可操作");
                return;
            }
            mAdapter.getData().remove(position);
            selectList.remove(position);
            mAdapter.notifyDataSetChanged();
        });
        mAdapter.addFooterView(footer);
        mAdapter.setFooterViewAsFlow(false);

    }

    @Subscriber(tag = RouterHub.RATING_SIGNUP3ACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.START_UPLOAD:
                SignUp3Data signUp3Data = (SignUp3Data) msg.obj;
                if (!signUp3Data.isUploading() && !signUp3Data.isUploadComplete()) {
                    mPresenter.upload(signUp3Data);
                }
                break;
            default:
        }
    }

    @Override
    public void showLoading() {
        if (mDialog == null) {
            mDialog = RxUtil.showLoading(getActivity(), "正在提交数据···");
        }
        mDialog.show();
    }

    @Override
    public void hideLoading() {
        if (ObjectUtils.isNotEmpty(mDialog)) {
            mDialog.dismiss();
        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(getActivity(), QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public void setUploadId(int position, long id) {
    }

    @Override
    public void update() {
        Message msg = Message.obtain();
        msg.what = EventBusTags.WORKS_UPLOAD_SUCCESS;
        EventBus.getDefault().post(msg, RouterHub.RATING_ENTRIESDETAILACTIVITY);
        EventBus.getDefault().post(msg, RouterHub.RATING_RATINGDETAILACTIVITY);
        EventBus.getDefault().post(msg, RouterHub.RATING_RATINGHOMEACTIVITY);
        Utils.customNavigation(RouterHub.RATING_UPLOADSUCCESSACTIVITY, Constants.COMPLETE, mHomeData);
        killMyself();
    }

    @Override
    public void onBackPressed() {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
        } else {
            super.onBackPressed();
        }
    }

    private boolean isUploading() {
        if (!lists.isEmpty()) {
            for (SignUp3Data list : lists) {
                if (list.isUploading()) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia localMedia = selectList.get(i);
                        if (lists.size() > i) {
                            if (lists.get(i).getLocalMedia().getPath().equals(localMedia.getPath())) {
                                continue;
                            } else {
                                lists.remove(i);
                                lists.add(new SignUp3Data().setLocalMedia(localMedia));
                            }
                        } else {
                            lists.add(new SignUp3Data().setLocalMedia(localMedia));
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                    break;
                default:
            }
        }
    }


    @OnClick(R2.id.btn_submit)
    public void onViewClicked() {
        if (isUploading()) {
            showMessage("上传完成后才可操作");
        } else {
            SignUp3Json json = new SignUp3Json();
            List<SignUp3Json.IdarrBean> idarrBeans = new ArrayList<>();
            SignUp3Json.IdarrBean idarrBean = new SignUp3Json.IdarrBean();
            idarrBean.setId(String.valueOf(mData.getId()));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < lists.size(); i++) {
                SignUp3Data list = lists.get(i);
                sb.append(list.getUploadId());
                if (i != lists.size() - 1) {
                    sb.append(",");
                }
            }
            sb.substring(0, sb.length() - 1);
            idarrBean.setRemoteIds(sb.toString());
            idarrBeans.add(idarrBean);
            json.setIdarr(idarrBeans);
            String jsonStr = mGson.toJson(json);
            mPresenter.saveFile(mData.getResearchId(), mData.getWorksId(), jsonStr);
        }
    }
}
